package com.platform.common.dataImport;

import com.platform.common.exception.BusinessException;
import com.platform.common.utils.Constant;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.Md5Utils;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.dataImport.BaseImportExcel;
import com.platform.modules.mall.entity.MallWhitelistEntity;
import com.platform.modules.mall.service.MallWhitelistService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class WhiteListImport extends BaseImportExcel {

    List<MallWhitelistEntity> entities = new ArrayList<>();
    private MallWhitelistService whitelistService;
    private int type;
    private int isMd5;
    private String lapseTime;

    {
        comparison = "姓名,身份证号(后6位),手机号码,次数,等级";
        format = new String[]{"name", "idCard", "phone", "number", "level"};
    }

    public WhiteListImport(MallWhitelistService whitelistService, int type, Integer isMd5, String lapseTime) {
        this.whitelistService = whitelistService;
        this.type = type;
        this.isMd5 = isMd5;
        this.lapseTime = lapseTime;
    }

    @Override
    public void major(String[] strs) {
        // 获取实体
        MallWhitelistEntity entity = toObj(strs, MallWhitelistEntity.class);
        entity.setValid(1);
        entity.setAddTime(new Date());
        entity.setLapseTime(DateUtils.stringToDate(lapseTime,DateUtils.DATE_TIME_PATTERN));
        entity.setType(type);
        if(Constant.ONE == isMd5){
            entity.setIdCard(StringUtils.isEmpty(entity.getIdCard())?"0":Md5Utils.encrypt(entity.getIdCard()));
            entity.setPhone(StringUtils.isEmpty(entity.getPhone())?"0":Md5Utils.encrypt(entity.getPhone()));
        }
        if (StringUtils.isBlank(entity.getAcctNo())) {
            // 卡号赋默认值
            entity.setAcctNo("0");
        }
        if (StringUtils.isBlank(entity.getIdCard())) {
            // 身份证号赋默认值
            entity.setIdCard("0");
        }
        if (StringUtils.isBlank(entity.getPhone())) {
            // 手机号赋默认值
            entity.setPhone("0");
        }
        entities.add(entity);
    }

    @Override
    public void after() {
        if (entities.isEmpty()) {
            throw new BusinessException("可导入的数据为0");
        }
        boolean result = whitelistService.saveBatch(entities);
        if (!result) {
            throw new BusinessException("导入失败，请检查数据或联系管理员");
        }
        super.after();
    }
}
